//
//  AppDelegate.m
//  CLBrowser
//
//  Created by chuck on 2021/6/30.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

#import "CLKeyboardHelper.h"
#import "CLMenuHelper.h"
#import "CLVCMain.h"
#import "CLWebServer.h"
#import "CLErrorPageHelper.h"
#import "CLSessionRestoreHelper.h"
#import "CLWebViewManager.h"
#import "CLUserDefaults.h"
#import "CLTabBarController.h"
#import "NSString+CLUtility.h"
#import "CLHTTPURLConfiguration.h"

static NSString * const kUserAgentOfiOS = @"Mozilla/5.0 (iPhone; CPU iPhone OS %ld_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/%ld.0 Mobile/14A300 Safari/602.1";

@interface AppDelegate ()

@property (nonatomic, assign) NSInteger pasteboardChangeCount;
@property (nonatomic, readwrite, strong) CLNavigationControllerStack *navigationControllerStack;
@end

@implementation AppDelegate

- (void)dealloc {
    [Notifier removeObserver:self name:UIPasteboardChangedNotification object:nil];
}

- (void)setAudioPlayInBackgroundMode {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    NSError *setCategoryError = nil;
    BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
    if (!success) { /* handle the error condition */ }
    
    NSError *activationError = nil;
    success = [audioSession setActive:YES error:&activationError];
    if (!success) { /* handle the error condition */ }
}

- (void)handlePasteboardNotification:(NSNotification *)notify {
    self.pasteboardChangeCount = [UIPasteboard generalPasteboard].changeCount;
}

- (void)presentPasteboardChangedAlertWithURL:(NSURL *)url {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"新窗口打开剪切板网址" message:@"您是否需要在新窗口中打开剪切板中的网址？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        NSNotification *notify = [NSNotification notificationWithName:kOpenInNewWindowNotification object:self userInfo:@{@"url": url}];
        [Notifier postNotification:notify];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}

- (void)makeWebViewSafariLike {
    NSOperatingSystemVersion systemVersion = [[NSProcessInfo processInfo] operatingSystemVersion];
    NSInteger version = systemVersion.majorVersion;

    NSString *userAgent = [NSString stringWithFormat:kUserAgentOfiOS, version, version];
    //解决UIWebView首次加载页面时间过长问题,设置UserAgent减少跳转和判断
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : userAgent}];
}

- (void)applicationStartPrepare {
    [self setAudioPlayInBackgroundMode];
    [[CLKeyboardHelper sharedInstance] startObserving];
    [[CLMenuHelper sharedInstance] setItems];
    
    [Notifier addObserver:self selector:@selector(handlePasteboardNotification:) name:UIPasteboardChangedNotification object:nil];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
        [[UITableView appearance] setEstimatedRowHeight:0];
        [[UITableView appearance] setEstimatedSectionFooterHeight:0];
        [[UITableView appearance] setEstimatedSectionHeaderHeight:0];
        [[UIWindow appearance] setBackgroundColor:[UIColor clearColor]];
    }
    
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                         diskCapacity:32 * 1024 * 1024
                                                             diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    
    // Config Service
    self.services = [[CLViewModelServicesImpl alloc] init];
    // Config Nav Stack
    self.navigationControllerStack = [[CLNavigationControllerStack alloc] initWithServices:self.services];
    
    [CLErrorPageHelper registerWithServer:[CLWebServer sharedInstance]];
    [CLSessionRestoreHelper registerWithServer:[CLWebServer sharedInstance]];
    
    [[CLWebServer sharedInstance] start];
    
    [self makeWebViewSafariLike];
    
    [CLWebViewManager sharedInstance];    //load archive data in advance
    
    [self.engine run];
    
    // Delay some operations
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self applicationStartPrepare];
    });
    
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    
    if (self.pasteboardChangeCount != pasteboard.changeCount) {
        self.pasteboardChangeCount = pasteboard.changeCount;
        NSURL *url = pasteboard.URL;
        if (url && ![[CLUserDefaults URLForKey:KeyPasteboardURL] isEqual:url]) {
            [CLUserDefaults setURL:url forKey:KeyPasteboardURL];
            [self presentPasteboardChangedAlertWithURL:url];
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application{
    [[NSUserDefaults standardUserDefaults] synchronize];
}

// Enable UIWebView video landscape
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    static NSString *kAVFullScreenViewControllerStr = @"AVFullScreenViewController";
    UIViewController *presentedViewController = [window.rootViewController presentedViewController];

    if (presentedViewController && [presentedViewController isKindOfClass:NSClassFromString(kAVFullScreenViewControllerStr)] && [presentedViewController isBeingDismissed] == NO) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}


- (UIWindow *)getRootWindow {
    UIWindow* window = nil;
    
    if (@available(iOS 13.0, *))
    {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                window = windowScene.windows.firstObject;
                
                break;
            }
        }
    }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    if (!window){
        window = [UIApplication sharedApplication].keyWindow;
    }
#pragma clang diagnostic pop
    return window;
}

- (FlutterEngine *)engine {
    if (!_engine) {
        _engine = [[FlutterEngine alloc] initWithName:@"flutter engine"];
    }
    return _engine;
}
@end
